import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import {reactive, ref, onMounted, toRaw, computed, h} from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  DangerSourceListCommand,
  getDangerSourceListApi,
  exportDangerSourceExcelApi,
  deleteDangerSourceApi
} from "@/api/airport/safetyManage/dangerSource";
import {useRouter} from "vue-router";

// 获取字典信息（可根据实际配置字典映射危险源状态）
const statusMap = useUserStoreHook().dictionaryMap["common.status"];

export function useDangerSourceHook() {

  const router = useRouter(); // 添加这行

  const handleReformClick = (row) => {
    if (row.relatedReformCode) {
      router.push({
        path: "/airport/reform/reformMain/index",
        query: { code: row.relatedReformCode }
      });
    }
  };

  const handleReportClick = (row) => {
    if (row.relatedQuestionId) {
      router.push({
        path: "/airport/safetyManage/reportList/index",
        query: { reportId: row.relatedQuestionId }
      });
    }
  };

  const defaultSort: Sort = {
    prop: "createTime",
    order: "descending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.beginTime && searchFormParams.endTime) {
        return [searchFormParams.beginTime, searchFormParams.endTime];
      } else {
        return null;
      }
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.beginTime = v[0];
        searchFormParams.endTime = v[1];
      } else {
        searchFormParams.beginTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });

  const searchFormParams = reactive<DangerSourceListCommand>({
    dangerSourceName: "",
    dangerType: undefined,
    sourceType: undefined,
  });

  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);
  const sortState = ref<Sort>(defaultSort);

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },

    {
      label: "编号",
      prop: "dangerSourceCode",
      minWidth: 120
    },
    {
      label: "名称",
      prop: "dangerSourceName",
      minWidth: 150
    },
    {
      label: "关联的整改任务",
      prop: "reformTittle",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ relatedReformCode, reformTittle }) => {
        if (!reformTittle || reformTittle === "") {
          return "无";
        }
        return h(
          "span",
          {
            style: {
              color: "#1890ff",
              cursor: "pointer",
              textDecoration: "underline"
            },
            onClick: () => handleReformClick({ relatedReformCode })
          },
          reformTittle
        );
      }
    },
    {
      label: "关联的安全信息",
      prop: "reportTittle",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ relatedQuestionId, reportTittle }) => {
        if (!reportTittle || reportTittle === "") {
          return "无";
        }
        return h(
          "span",
          {
            style: {
              color: "#1890ff",
              cursor: "pointer",
              textDecoration: "underline"
            },
            onClick: () => handleReportClick({ relatedQuestionId })
          },
          reportTittle
        );
      }
    },
    {
      label: "责任部门",
      prop: "dutyDeptName",
      minWidth: 120
    },
    {
      label: "措施责任部门",
      prop: "actionDeptName",
      minWidth: 120
    },
    {
      label: "危害描述",
      prop: "harmDescribe",
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      label: "根本原因",
      prop: "rootCause",
      minWidth: 180,
      showOverflowTooltip: true
    },

    {
      label: "责任人",
      prop: "actionMakerName",
      minWidth: 120
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      sortable: "custom",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    pagination.currentPage = 1;
    getDangerSourceList();
  }

  async function onSearch(tableRef) {
    tableRef.getTableRef().sort("createTime", "descending");
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    formEl.resetFields();
    searchFormParams.beginTime = undefined;
    searchFormParams.endTime = undefined;
    onSearch(tableRef);
  }

  async function getDangerSourceList() {
    pageLoading.value = true;
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);

    const { data } = await getDangerSourceListApi(toRaw(searchFormParams)).finally(() => {
      pageLoading.value = false;
    });

    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function exportAllExcel() {
    if (sortState.value != null) {
      CommonUtils.fillSortParams(searchFormParams, sortState.value);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    exportDangerSourceExcelApi(toRaw(searchFormParams), "危险源数据.xlsx");
  }

  async function handleDelete(row) {
    await deleteDangerSourceApi([row.dangerSourceId]).then(() => {
      message(`您删除了编号为 ${row.dangerSourceId} 的危险源`, {
        type: "success"
      });
      getDangerSourceList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的危险源吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteDangerSourceApi(multipleSelection.value).then(() => {
          message(`您删除了编号为 [ ${multipleSelection.value} ] 的危险源`, {
            type: "success"
          });
          getDangerSourceList();
        });
      })
      .catch(() => {
        message("取消删除", { type: "info" });
        tableRef.getTableRef().clearSelection();
      });
  }

  onMounted(getDangerSourceList);

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    timeRange,
    multipleSelection,
    onSearch,
    onSortChanged,
    exportAllExcel,
    getDangerSourceList,
    resetForm,
    handleDelete,
    handleBulkDelete
  };
}
